"""
Stephen Herbein, Ronald Lewis, Kyle Tucker, CISC220080, Dr. Atlas

Gets traffic data and accident/construction data from a webpage then outputs
it as a .gif and .txt file respectively
"""

import urllib2
from httplib import *
import os

# Gets an image from a webpage that represents traffic and writes it to
# a .gif file
picture_page = "http://www.mapquestapi.com/traffic/v1/flow?key=Fmjtd|luu2n9uzl1%2C80%3Do5-harlg&projection=merc&mapLat=39.684094513409825&mapLng=-75.75017386054219&mapHeight=400&mapWidth=400&mapScale=433343"
opener1 = urllib2.build_opener()
page1 = opener1.open(picture_page)
my_picture = page1.read()
fout = open("flow.gif", "wb")
fout.write(my_picture)
fout.close()

# Gets construction and accident data from a webpage
connection = HTTPConnection("www.mapquestapi.com")
connection.request("GET","/traffic/v1/incidents?key=Fmjtd|luu2n9uzl1%2C80%3Do5-harlg&callback=handleIncidentsResponse&boundingBox=39.786533138147725,-75.87651663397463,39.575152875837226,-75.6018584308606&filters=construction,incidents&inFormat=kvp&outFormat=xml")
response = connection.getresponse()
mapquestOutput = response.read()
connection.close()

# Writes the construction and accident data to a .txt file
output = open("incidentData.txt","w")
remainingData = True
line = ""
# Continues until no more data remains
while(remainingData):
    try:
        # Gets the longitude data
        startIndex = mapquestOutput.index("<lng>") + 5
        # Index is for <, plus 5 leads to first digit in longitude
        endIndex = mapquestOutput.index("</lng>")
        line = mapquestOutput[startIndex:endIndex] + ","

        # Gets the latitude data
        startIndex = mapquestOutput.index("<lat>") + 5
        # Index is for <, plus 5 leads to first digit in latitude
        endIndex = mapquestOutput.index("</lat>")
        line += mapquestOutput[startIndex:endIndex] + ":"

        # Gets the seveerity data
        startIndex = mapquestOutput.index("<severity>") + 10
        # Index is for <, plus 10 leads to first digit in latitude
        endIndex = mapquestOutput.index("</severity>")
        line += mapquestOutput[startIndex:endIndex] + ";"

        # Writes the data to the .txt file
        output.write(line)
        # Eliminates the data already considered
        mapquestOutput = mapquestOutput[endIndex:]
        
    # Triggers when no more data is contained
    except (ValueError):
        # Set a variable to end the loop
        remainingData = False
output.close()
